/**
 * 认证相关接口
 */

import { post, put } from '@/utils/request'

// 通用 API 响应
interface ApiResponse<T> {
    success: boolean
    statusCode: number
    message: string
    data: T
}

const unwrap = <T>(response: ApiResponse<T>): T => response.data

// 用户信息接口
export interface UserInfo {
    id: number
    username?: string
    email?: string | null
    phone?: string | null
    openid?: string
    unionid?: string | null
    nickname?: string
    avatar?: string | null
    isActive?: boolean
    createdAt?: string
    updatedAt?: string
    friendsCount?: number | 0 // 好友总数（登录时返回）
    followersCount?: number | 0 // 粉丝数
    followingCount?: number | 0 // 关注数
    receivedLikesCount?: number | 0 // 获赞数
}

// 登录响应接口
export interface LoginResponse {
    user: UserInfo
    accessToken: string
    refreshToken?: string // 小程序端会返回 refresh token
}

// 微信登录请求参数
export interface WechatLoginParams {
    code: string
    encryptedData?: string
    iv?: string
    nickname?: string
    avatarUrl?: string
    gender?: number
}

// 手机号登录请求参数
export interface PhoneLoginParams {
    phone: string
    code: string
}

// 账号密码登录请求参数
export interface AccountLoginParams {
    account: string      // 用户名或手机号
    password: string
}

// 用户注册请求参数
export interface RegisterParams {
    username: string     // 用户名
    phone: string        // 手机号
    password: string     // 密码
    email: string // 邮箱
    nickname?: string    // 昵称（可选）
}

// Token 刷新响应
export interface RefreshTokenResponse {
    accessToken: string
    tokenType: string
    expiresIn: number
}

/**
 * 微信小程序登录
 */
export const wechatLogin = (params: WechatLoginParams): Promise<LoginResponse> => {
    return post<ApiResponse<LoginResponse>>('/auth/wechat-login', params, {
        showLoading: true,
        loadingText: '登录中...'
    }).then(unwrap)
}

/**
 * 手机号验证码登录
 */
export const phoneLogin = (params: PhoneLoginParams): Promise<LoginResponse> => {
    return post<ApiResponse<LoginResponse>>('/auth/phone-login', params, {
        showLoading: true,
        loadingText: '登录中...'
    }).then(unwrap)
}

/**
 * 账号密码登录
 * 支持用户名或手机号登录
 */
export const accountLogin = (params: AccountLoginParams): Promise<LoginResponse> => {
    return post<ApiResponse<LoginResponse>>('/auth/login', params, {
        showLoading: true,
        loadingText: '登录中...'
    }).then(unwrap)
}

/**
 * 用户注册
 */
export const register = (params: RegisterParams): Promise<LoginResponse> => {
    return post<ApiResponse<LoginResponse>>('/auth/register', params, {
        showLoading: true,
        loadingText: '注册中...'
    }).then(unwrap)
}

/**
 * 发送验证码
 */
export const sendSmsCode = (phone: string): Promise<{ message: string }> => {
    return post<ApiResponse<{ message: string }>>('/auth/send-sms', { phone }).then(unwrap)
}

/**
 * 刷新 Token
 */
export const refreshAccessToken = (): Promise<RefreshTokenResponse> => {
    return post<ApiResponse<RefreshTokenResponse>>('/auth/refresh').then(unwrap)
}

/**
 * 登出
 */
export const logout = (): Promise<{ message: string }> => {
    return post<ApiResponse<{ message: string }>>('/auth/logout').then(unwrap)
}

/**
 * 登出所有设备
 */
export const logoutAllDevices = (): Promise<{ message: string }> => {
    return post<ApiResponse<{ message: string }>>('/auth/logout-all').then(unwrap)
}

// 更新用户信息参数
export interface UpdateUserParams {
    username?: string
    email?: string
    phone?: string
    nickname?: string
    avatar?: string
    gender?: 'male' | 'female' | 'other'
    birthday?: string
    bio?: string
}

/**
 * 更新用户信息
 */
export const updateUser = (userId: number, params: UpdateUserParams): Promise<UserInfo> => {
    return put<UserInfo>(`/auth/user/${userId}`, params)
}

export default {
    wechatLogin,
    phoneLogin,
    accountLogin,
    register,
    sendSmsCode,
    refreshAccessToken,
    logout,
    logoutAllDevices,
    updateUser
}

